<?php

/*
 * Created on 2013-1-27
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'boss.class.php';
//替换GET参数
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'cdn/cdn_parameter_conversion.class.php';
include_once dirname(dirname(dirname(__FILE__))) . "/nn_cms_config/nn_cms_function.php";
$mgtvParamenter = array(
    'aa' => 'nns_tag',
    'ab' => 'nns_func',
    'ac' => 'nns_video_id',
    'ad' => 'nns_video_type',
    'ae' => 'nns_mode',
    'af' => 'nns_before_day',
    'ag' => 'nns_after_day',
    'ah' => 'nns_search_key',
    'ai' => 'nns_page_index',
    'aj' => 'nns_page_size',
    'ak' => 'nns_media_assets_id',
    'al' => 'nns_category_id',
    'am' => 'nns_sort_type',
    'an' => 'nns_include_category',
    'ao' => 'nns_video_label_id',
    'ap' => 'nns_label_type_id',
    'aq' => 'nns_product_id',
    'ar' => 'city_id',
    'as' => 'area_code',
    'av' => 'nns_output_type',
    'ax' => 'nns_user_agent'
);




/**
 * 芒果TV公用返回状态信息
 */
$status = array(
    '40000' => 'Guest认证成功，返回Guest帐号',
    '40001' => 'Mac地址认证失败',
    '40002' => 'EPG认证失败，返回Guest帐号',
    '40003' => 'Token认证失败，返回Guest帐号',
    '40004' => 'Token认证成功，用户认证成功',
    '40005' => '需要订购',
    '40006' => '免费',
    '40007' => '播放广告后可观看',
    '40008' => '参数错误',
    '40009' => 'IP地址非法',
    '40010' => '其他错误',
    '40011' => '获取下载数据出错',
    '40012' => '已授权',
    '40013' => '获取数据异常',
    '40014' => '续订/取消续订操作失败',
    '40015' => 'IP地址认证失败',
    '20000' => '账户验证成功',
    '20001' => '参数不存在、参数错误',
    '20002' => '批价错误、订单已存在',
    '20003' => '扣账户余额失败',
    '20004' => '交易码不存在或已过期',
    '20005' => '订单还未支付',
    '20006' => '请求超时,请返回重试',
    '20007' => '用户中心接口出错',
    '20008' => '账户验证失败',
    '20009' => '充值中心内部错误',
    '20010' => '订单状态查询接口返回失败',
    '20011' => '影片已经购买',
    '21000' => '需要进行二次身份认证',
    '21001' => '易联语音身份认证失败',
    //自定义
    '999001' => '余额不足',
    '999002' => '未完成付款',
    '999003' => '第三方通知支付失败',
    '999004' => '已完成付款,但尚未开通服务',
    '999005' => '已开通服务',
);

//$mgtv_UI = array(
//    'pay' => 'http://58.83.191.25/OTTBossApi/StartPay.ashx',
//);





function get_reason($key,$reason="") {
	//if(empty($reason)||$reason==""){
			global $status;
	        return isset($status[$key]) ? $status[$key] : "";
	//}else{
	//	return $reason;
	//}
        
}


function get_reason_other($key,$reason="") {
	if(empty($reason)||$reason==""){
			global $status;
	        return isset($status[$key]) ? $status[$key] : "";
	}else{
		return $reason;
	}
        
}

include 'mgtv_cdn_jump_url.php'; //*接口名替换规则数组*/

function check_valid_by_webtoken() {
        $valid_params = array();
        $valid_params['mode'] = 'ott_tv';
        $valid_params['tv_id'] = $_GET['nns_device_id'];
        $valid_params['net_id'] = $_GET['nns_net_id'];
        $valid_params['mac_id'] = $_GET['nns_mac_id'];
        $valid_params['token'] = $_GET['nns_webtoken'];
        $valid_params['version'] = $_GET['nns_version'];
        $valid_params['ex_data'] = $_GET['nns_ex_data'];
        $boss = boss::get();
        $response_new = $boss->auth_by_token($valid_params);

        if (isset($response_new['err'])) {
                $response = $response_new['msg'];
                $err = $response_new['err'];
                $reason = $response_new['reason'];
        } else {
                $response = $response_new;
                $err = $response_new['ret'];
                if ($err == 0) {
                        $reason = '认证成功！';
                } else {
                        $reason = '认证失败！';
                }
        }

//	var_dump($response);die;
        $response['token'] = $response['new_token'];
        switch ($err) {
                case '0':
                        $state = '0';
                        break;
                case '1':
                        $state = '1';

                        break;
        }
        //	测试数据
//		$response=array('user_id'=>'1');	
        return array('state' => $state, 'reason' => $reason, 'response' => $response, 'status' => $response_new['status']);
}

//芒果TV专用

function get_mgtv_assets_ids() {
        $boss = boss::get();
        if ($_GET['nns_sort_type'] == 'click') {
                $sort = 'hot';
        } else {
                $sort = 'new';
        }

        $result = $boss->get_assets(array(
            'svc_item_id' => $_GET['nns_product_id'],
            'page_index' => $_GET['nns_page_index'],
            'page_size' => $_GET['nns_page_size'],
            'sort' => $sort,
            'token' => $_GET['nns_webtoken'],
            'version' => $_GET['nns_version'],
            'ex_data' => $_GET['nns_ex_data']
        ));



        if (is_array($result)) {
                if (isset($result['err'])) {
                        $response = $result['msg'];
                        $err = $result['err'];
                } else {
                        $response = $result;
                        $err = $result['ret'];
                }
                $reason = $result['reason'];


                return array('state' => $err, 'reason' => $reason, 'response' => $response, 'status' => $result['status']);
        } else {
                return $result;
        }
}

// 获取计费信息
function get_mgtv_boss_fee($asset_id) {
        $boss = boss::get();
        $result = $boss->play_auth(array(
            'user_id' => $_GET["nns_user_id"],
            'tv_id' => $_GET["nns_device_id"],
            'token' => $_GET["nns_webtoken"],
            'mac_id' => $_GET['nns_mac_id'],
            'asset_id' => $asset_id,
//		'asset_id'=>'8908',
            'asset_type' => $_GET["nns_video_type"],
            'net_id' => $_GET['nns_net_id'],
            'version' => $_GET['nns_version'],
            'ex_data' => $_GET['nns_ex_data']
        ));



        if (is_array($result)) {

                if (isset($result['err'])) {
                        $response = $result['msg'];
                        $status = $result['status'];
                        $err = 0;
                        switch ($status) {
                                case '40005':
                                        $reason = '未授权';
                                        $err = 1;
                                        break;
                                case '40006':
                                        $reason = '免费';
                                        $err = 2;
                                        break;
                                case '40007':
                                        $reason = '播放广告后观看';
                                        $err = 3;
                                        break;
                                case '40012':
                                        $reason = '已授权';
                                        $err = 0;
                                        break;
                                default :
                                        $reason = '错误';
                                        $err = '-1';
                                        break;
                        }
                        $boss_urls = g_cms_config::get_g_config_value("g_boss_url");
                        $base_url = $boss_urls['pay_ui'];
                        if (strpos($base_url, '?')) {
                                $base_url.='&svc_item_id=' . $response['svc_item_id'];
                        } else {
                                $base_url.='?svc_item_id=' . $response['svc_item_id'];
                        }
                        $response['url'] = $base_url;
                } else {
                        $response = $result;
                        $err = $result['ret'];
                        switch ($err) {
                                case '0':
                                        $reason = '已授权';
                                        break;
                                case '1':
                                        $reason = '未授权';
                                        break;
                                case '2':
                                        $reason = '免费';
                                        break;
                                case '3':
                                        $reason = '播放广告后观看';
                                        break;
                        }
                }
        } else {
//		返回错误
                return $result;
        }



        return array('state' => $err, 'reason' => $reason, 'response' => $response, 'status' => $status);
}

// 获取播放串信息
/**
 * user_id	用户ID
  user_ip	用户IP
  file_id	片源ID
  content_id	内容ID
  content_url	物理路径   URL编码
  ...	其它可能需要的辅助信息
  time_limit	0 或是未传，不限制
  其它值，代表仅允许用户预看这个时间长度，比如10分钟，服务器应推送比这个值略长的数据，终端将实现进度条到达指定时间时，弹出提示用户购买。
 */
function get_play_url_by_mgtv($media) {
        global $status;
        $boss = boss::get();
        $result = $boss->get_play_url(
                array(
                    'user_id' => $_GET["nns_user_id"],
                    'user_ip' => $_SERVER['REMOTE_ADDR'],
                    'token' => $_GET["nns_webtoken"],
                    'content_id' => $media['nns_import_index_id'],
                    'content_url' => $media['nns_url'],
                    'file_id' => $media['nns_import_id'],
                    'time_limit' => 0,
                    'version' => $_GET['nns_version'],
                    'ex_data' => $_GET['nns_ex_data']
        ));

        if (isset($result['err'])) {

                $response = $result['msg'];

                $response['ret'] = $result['err'];
                $response['reason'] = $result['reason'];
        } else {
                $response = $result;
        }


        return $response;
}

function get_mgtv_boss_valid($params) {
        $valid_params = array();
        $valid_params['mode'] = 'ott_tv';
        $valid_params['tv_id'] = $params['nns_device_id'];
        $valid_params['net_id'] = $params['nns_net_id'];
        $valid_params['mac_id'] = $params['nns_mac_id'];
        $valid_params['token'] = $params['nns_webtoken'];
        $valid_params['version'] = $params['nns_version'];
        $valid_params['ex_data'] = $params['nns_ex_data'];

        $boss = boss::get();

        $result = $boss->auth($valid_params);

        if (!is_array($result)) {
                return $result;
        }

        if (isset($result['err'])) {
                $response = $result['msg'];
                $response['token'] = $response['new_token'];
                /**
                 * '40000'=>'Guest认证成功，返回Guest帐号',
                  '40001'=>'Mac地址认证失败',
                  '40002'=>'EPG认证失败，返回Guest帐号',
                  '40003'=>'Token认证失败，返回Guest帐号',
                  '40004'=>'Token认证成功，用户认证成功',
                 * '40015'=>'IP地址认证失败

                 */
                switch ($result['status']) {
                        case '40000':
                                $state = 0;
                                break;
                        case '40001':
                                $state = 5;
                                break;
                        case '40002':
                                $state = 0;
                                break;
                        case '40003':
                                $state = 0;
                                break;
                        case '40004':
                                $state = 0;
                                break;
                        case '40015':
                                $state = 7;
                                break;
                }
                $reason = $result['reason'];
        } else {
                $response = $result;
//	var_dump($response);die;
                $response['token'] = $response['new_token'];
                switch ($response['ret']) {
                        case '0':
                                $state = '0';
                                $reason = 'Guest认证成功，返回Guest帐号';
                                break;
                        case '1':
                                $state = '5';
                                $reason = 'Mac地址认证失败（提示用户，不能进入）';

                                break;
                        case '2':
//            $state = '4';
                                $reason = 'EPG认证失败，返回Guest帐号';
                                $state = '0';
                                break;
                        case '3':
//            $state = '2';
                                $reason = 'token认证失败，返回Guest帐号';
                                $state = '0';
                                break;
                        case '4':
                                $valid_params['token'] = $response['new_token'];

                                $state = '0';
                                $reason = 'token 认证成功， 用户认证成功';
//				return get_mgtv_boss_valid($valid_params);
                                break;
                }
        }

        //	测试数据
//		$response=array('user_id'=>'1');	
        return array('state' => $state, 'reason' => $reason, 'response' => $response, 'status' => $result['status']);
}

/**
 * yxt
 * mgtv专用
 * @param array $media 片源信息
 * @param 0/1 $state
 * @param string $out_url 输出的url
 */
function get_play_url_by_starcor($media_data, $video_name, $params, $env) {
        include_once $env->nl_path . 'npss' . DIRECTORY_SEPARATOR . 'npss.class.php';
        include_once $env->np_path . 'curl.class.php';
        $core_npss_url = nl_npss::get_active_npss_address();

        $remot_ip = $_SERVER["REMOTE_ADDR"];
        $t = time();
        $time = date("Ymd", $t) . 'T' . date("His", $t) . 'Z';

        $guid_id = np_guid_rand();
        $nn_kd = md5($media_data['nns_content_id'] . $params['nns_user_id'] . '123456' . time() . $guid_id);

//		修改为每个参数判断是否为空，非空则传 ---BY S67
//        if ($_GET['nns_day'] && $_GET['nns_time_len'] && $_GET['nns_begin']) {
//                $extend_url = '&nn_day=' . $_GET['nns_day'] . '&nn_time_len=' . $_GET['nns_time_len'] . '&nn_begin=' . $_GET['nns_begin'];
//        }

        $extend_url = "";
        if (!empty($_GET['nns_day'])) {
                $extend_url .= '&nn_day=' . $_GET['nns_day'];
        }
        if (!empty($_GET['nns_begin'])) {
                $extend_url .= '&nn_begin=' . $_GET['nns_begin'];
        }
        if (!empty($_GET['nns_time_len'])) {
                $extend_url .= '&nn_time_len=' . $_GET['nns_time_len'];
        }


        //设置post地址
        $url = "http://" . $core_npss_url . "/nn_live.ts?id={$media_data['nns_content_id']}&nn_from_epg_server=1&nn_ua_ips={$remot_ip}&nn_user_id={$params['nns_user_id']}&nn_kt={$time}&nn_kv=1&nn_kr={$guid_id}&nn_kd={$nn_kd}" . $extend_url;
//       var_dump($url);die;
        //获取ip
//	return array('0','OK',$url);
        $cu = new curl();


//	//调试yxt2013年3月11日10:02:27，去我们的媒体服务器获取播放串
////	下面2行用于计算执行时间上线之后删除
//	list($usec, $sec) = explode(' ', microtime()); 
//	$GLOBALS['start_starcor']=((float)$usec + (float)$sec); 
//	
        $re = $cu->get($url); //这行别删
//	
//	//调试yxt下面3行用于计算执行时间，上线之后删除
//	list($usec, $sec) = explode(' ', microtime()); 
//	$GLOBALS['end_starcor']=((float)$usec + (float)$sec); 
//	$GLOBALS['live_url']=$url;





        $info = explode("\n", $re);
        //获取错误码
        $error_reason = explode(":", $info[1]);
        $error_code = explode(":", $info[0]);
        $info[0] = $error_code[1];
        $info[1] = $error_reason[1];
        //获取播放地址:
        $play_url["http"] = str_replace("play_url:", "", $info[2]);
        $info[2] = $play_url["http"];
        //写入错误日志
        if ($error_code[1] != '0') {

                //以下为调试代码
                $handle = fopen(dirname(dirname(dirname(__FILE__))) . '/data/log/' . "get_play_url_error_log.txt", "a");
                fwrite($handle, '################################IP_ADDRESS:' . $_SERVER["REMOTE_ADDR"] . '   DATE:' . date("Y-m-n H:i:s", time()) . "nns_func=" . $_REQUEST['nns_func'] . "\r\n");
                $url1 = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
                fwrite($handle, "REMOTE_URL:{$url1}\r\n");
                fwrite($handle, "SERVER_URL:{$url}\r\n");
                fwrite($handle, "GET_PLAY_URL:{$play_url["http"]}\r\n");
                fwrite($handle, "CURL_ERROR:" . $cu->error());
                foreach ($_REQUEST as $key => $val) {
                        fwrite($handle, $key . '=' . $val . "\r\n");
                }
                fwrite($handle, "output:\r\n" . $play_url["http"] . "\r\n");
                fclose($handle);
                //以上为调试代码
        }
        return $info;
}

function notice_boss_live_add($live_id, $live_name, $live_type) {
        $boss = boss::get();
        $result = $boss->live_add(
                array(
                    'live_id' => $live_id,
                    'live_name' => $live_name,
                    'live_type' => $live_type
                )
        );
        if ($result['ret'] == 0) {
                return TRUE;
        } else {
                //yxt如果添加直播失败写入日志
                $handle = fopen(dirname(dirname(dirname(__FILE__))) . '/data/log/mgtv_boss/' . "error_addlive.txt", "a");
                fwrite($handle, "################################add_time:" . date("Y-m-n H:i:s", time()) . "\r\n");
                fwrite($handle, "to_params:\r\n");
                fwrite($handle, "live_id:{$live_id}\r\n");
                fwrite($handle, "live_name:{$live_name}\r\n");
                fwrite($handle, "live_type:{$live_type}\r\n");
                fwrite($handle, "ret:{$result['ret']}\r\n");
                fwrite($handle, "reason:{$result['reason']}\r\n");
                fclose($handle);
                return FALSE;
        }
}

function notice_boss_live_del($live_id) {
        $boss = boss::get();
        $result = $boss->live_del(
                array(
                    'live_id' => $live_id,
                )
        );
        if ($result['ret'] == 0) {
                return TRUE;
        } else {
                //yxt如果添加直播失败写入日志
                $handle = fopen(dirname(dirname(dirname(__FILE__))) . '/data/log/mgtv_boss/' . "error_dellive.txt", "a");
                fwrite($handle, "################################del_time:" . date("Y-m-n H:i:s", time()) . "\r\n");
                fwrite($handle, "to_params:\r\n");
                fwrite($handle, "live_id:{$live_id}\r\n");
                fwrite($handle, "ret:{$result['ret']}\r\n");
                fwrite($handle, "reason:{$result['reason']}\r\n");
                fclose($handle);
                return FALSE;
        }
}

function replaceGetKey() {
        global $mgtvParamenter;
        $mgtv_cdn_get_replace = g_cms_config::get_g_config_value('g_cdn_enabled'); //是否替换芒果TV的GET键值
        if (!$mgtv_cdn_get_replace) {
                return false;
        }
        set_replace_str(); //解析替换CDN静态变量
        return cdn_parameter_conversion::setGetParameter($mgtvParamenter);
}

/* test URL
 * /nn_cms_view/mgtv/n1_a.php?a=aakdsfhksajdfhkl-bbasdasdwerewrwer-ccwqeqweqwewqe-aakdsfhksajdfhkl-bbasdasdwerewrwer-ccwqeqweqwewqe-ddehehehehee
 */

function set_replace_str() {
        $actionName = 'a';
        if (!isset($_GET[$actionName]) || empty($_GET[$actionName])) {
                return false;
        }
        $str = $_GET[$actionName];
        @preg_match_all('/(?<key>\w*)__(?<val>[^--]*)/is', $str, $getArr, PREG_SET_ORDER);
        if (!is_array($getArr))
                return false;
        unset($_GET[$actionName]);
        foreach ($getArr as $getv) {
                $_GET[$getv['key']] = $getv['val'];
        }
        return true;
}

/*
 * 替换接口名字
 */

function set_replace_url_str($output_type, $data) {
        global $g_cdn_enabled;
        if (empty($data) || !$g_cdn_enabled)
                return $data;
        if ($output_type == 'json')
                $xmlData = set_replace_json($data);
        else
                $xmlData = set_replace_xml($data);
        return $xmlData;
}

function set_replace_xml($xmlHtml) {
        global $fileNameArr, $g_webdir;
        $url = parse_url($g_webdir);
        $url = $url['scheme'] . "://" . $url['host'];
        $preg = "/url=\"(http.*\/nn_cms_view\/(?<mgtvdir>[^\/].*)\/(?<name>.*)\.php)/isU";
        preg_match_all($preg, $xmlHtml, $htmlUrl);
        $dirName = empty($htmlUrl['mgtvdir'][0]) ? 'mgtv' : $htmlUrl['mgtvdir'][0];
        foreach ($htmlUrl[1] as $num => $val) {
                $fileName = strtoupper($htmlUrl['name'][$num]);
                if (isset($fileNameArr[$fileName])) {
                        $newDir = $url . '/' . $dirName . '/' . $fileNameArr[$fileName];
                        $xmlHtml = str_replace($val, $newDir, $xmlHtml);
                }
        }
        return $xmlHtml;
}

function set_replace_json($json, $jsontype = true) {
        global $fileNameArr, $g_webdir;
        $url = parse_url($g_webdir);
        $url = $url['scheme'] . "://" . $url['host'];
        $json = $jsontype ? json_decode($json, true) : $json;

        foreach ($json as $name => $val) {
                if (isset($val['group']))
                        continue;
                if (isset($val['url'])) {
                        $fileName = strtoupper($name);
                        $preg = "/http.*\/.*nn_cms_view\/(?<mgtvdir>[^\/].*)\/(?<name>.*)\.php(?<a>.*)$/isU";
                        preg_match($preg, $val['url'], $htmlUrl);
                        if (isset($fileNameArr[$fileName])) {
                                $get = set_replace_get($htmlUrl['a']);
                                $json[$name]['url'] = $url . '/' . $htmlUrl['mgtvdir'] . '/' . $fileNameArr[$fileName] . $get;
                        }
                } elseif (is_array($val)) {
                        $json[$name] = set_replace_json($val, false);
                }
        }
        $json = $jsontype ? json_encode($json) : $json;
        return $json;
}

function set_replace_get($get) {
        if (empty($get))
                return $get;
        $get = str_replace('?', '', $get);
        parse_str($get, $arr);
        foreach ($arr as $k => $v) {
                $strArr = explode('_', $k);
                if (count($strArr) >= 2) {
                        foreach ($strArr as $k2 => $v2) {
                                if ($v2 == 'nns') {
                                        unset($strArr[$k2]);
                                        continue;
                                }
                                $strArr[$k2] = ucfirst($v2);
                        }
                        $k = implode('', $strArr);
                }
                $GET[$k] = $v;
        }
        return "?" . http_build_query($GET);
}

?>
